//
//  IWHChargeManager.m
//  WangHuo
//
//  Created by HappyWork on 2019/2/27.
//  Copyright © 2019 ifeng. All rights reserved.
//

#import "IWHChargeManager.h"

#if __has_include("IWHRequest.h")
#define IWHRequestIncluded
#endif


@interface IWHChargeManager () <ILGPayDelegate>
@property (nonatomic, strong) NSMutableDictionary *blockDict;
@end

@implementation IWHChargeManager

static IWHChargeManager *_manager;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[IWHChargeManager alloc] init];
    });
    return _manager;
}

- (void)pay:(NSString *)productId completion:(IWHPayCompletion)completion {
#ifdef IWHRequestIncluded
    [self p_createOrder:IWHURL_CreateOrder params:@{@"productId":productId} completion:completion callback:^(NSString *orderId) {
        [self.payKit iap_pay:productId orderId:orderId];
    }];
#endif
}


#pragma mark - getter

- (ILGPay *)payKit {
    if (!_payKit) {
        _payKit = [[ILGPay alloc] init];
        _payKit.delegate = self;
    }
    return _payKit;
}

- (NSDictionary *)blockDict {
    if (!_blockDict) {
        _blockDict = [[NSMutableDictionary alloc] init];
    }
    return _blockDict;
}


#pragma mark - delegate

- (void)chargeComplete:(NSDictionary *)result error:(NSError *)error {
    if (error) {
        [self p_orderCompleted:result[@"orderId"] result:nil error:error];
    } else {
        [self p_noticePlatformServer:result];
        
        // 按需查询订单状态
        if (self.blockDict[result[@"orderId"]]) {
            [self lookupOrderState:result[@"orderId"]];
        }
    }
}

#pragma mark - server
- (void)p_get:(NSString *)urlStr params:(NSDictionary *)params success:(void(^)(NSDictionary *result))success failure:(void(^)(NSError *error))failure {
#ifdef IWHRequestIncluded
    [IWHRequest get:urlStr parameter:params success:success failure:failure];
#endif
}
- (void)p_createOrder:(NSString *)urlStr params:(NSDictionary *)params completion:(IWHPayCompletion)completion callback:(void(^)(NSString *orderId))callback {
    __weak typeof(self)weakSelf = self;
    [self p_get:urlStr params:params success:^(NSDictionary *result) {
        
        NSString *orderId = [NSString stringWithFormat:@"%@", result];
        
        if (completion) {
            [weakSelf.blockDict setObject:[completion copy] forKey:orderId];
        }
        
        callback ? callback(orderId):nil;
        
        //        [[ZCFMDBManager shareInstance] saveChargeLog:[NSString stringWithFormat:@"创建预订单成功, pay:completion:"] orderId:payItem.orderId];
    } failure:^(NSError *error) {
        //        [[ZCFMDBManager shareInstance] saveChargeLog:[NSString stringWithFormat:@"创建预订单失败, errMsg=%@, errCode=%d, pay:completion:", error.localizedDescription, (int)error.code] orderId:nil];
        
        completion ? completion(error, nil):nil;
    }];
}

// 内购扣款成功，通知商家服务器
- (void)p_noticePlatformServer:(NSDictionary *)result {
#ifdef IWHRequestIncluded
    NSString *transactionIdentifier = result[@"transactionIdentifier"];
    NSString *receipt = result[@"receipt"];
    NSString *orderId = result[@"orderId"];
    
    NSDictionary *parameter = @{@"receipt":receipt,
                                @"rechargeId":orderId,
                                @"transactionIdentifier":transactionIdentifier
                                };
    
     __weak typeof(self)weakSelf = self;
     IWHRequest *request = [[IWHRequest alloc] initWithBaseURL:IWHApiBaseURL];
     [request setRequestSerializer:ILGRequestSerializerHTTP];
     [request post:IWHURL_CheckOrder parameter:parameter success:^(NSDictionary *dic) {
         // 服务端已经收到支付票据，结束与苹果的交易
         [weakSelf.payKit iap_finishTransaction:orderId];
     
     } failure:^(NSError *error) {
     
     }];
#endif
}

static int kLoopCountForLookupOrderState = 0;
static NSDate *kRecordDate = nil;
- (void)lookupOrderState:(NSString *)orderId {
    kRecordDate = [NSDate date]; //开始计时
    kLoopCountForLookupOrderState = 0;
    
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(loopForOrderState:) userInfo:@{@"orderId":orderId} repeats:YES];
        
        [weakSelf loopForOrderState:timer];
    });
}
- (void)loopForOrderState:(NSTimer *)timer {
    NSString *orderId = timer.userInfo[@"orderId"];
    
    // 超时处理
    NSString *timeLength = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSinceDate:kRecordDate]];
    kLoopCountForLookupOrderState++;
    if (timeLength.intValue >= 10 || kLoopCountForLookupOrderState > 3) {
        NSError *error = [NSError errorWithDomain:@"com.ilgPay.error" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"支付超时"}];
        [self p_orderCompleted:orderId result:nil error:error];

        [timer invalidate];
        kRecordDate = nil;
        
        return;
    }
#ifdef IWHRequestIncluded
    __weak typeof(self) weakSelf = self;
    [self p_get:IWHURL_LookOrder params:@{@"rechargeId":orderId} success:^(NSDictionary *result) {
        kRecordDate = nil;
        [timer invalidate];
        
        [weakSelf p_orderCompleted:orderId result:result error:nil];
        
    } failure:^(NSError *error) {
        if (error.code == -3) { //订单未完成
            //次数可以给用户点温馨小提示，以缓解用户焦急的心情
            
        } else {
            NSError *error = [NSError errorWithDomain:@"com.ilgPay.error" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"支付失败"}];
            [weakSelf p_orderCompleted:orderId result:nil error:error];
        }
    }];
#endif
}


#pragma mark - other

- (void)p_orderCompleted:(NSString *)orderId result:(NSDictionary *)result error:(NSError *)error {
    IWHPayCompletion completion = self.blockDict[orderId];
    
    if (completion) {
        completion(error, result);
    }
    
    [self.blockDict removeObjectForKey:orderId];
}

@end
